<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" label-width="110px" class="search-form"
      v-show="showSearch">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="始发地企业" prop="startCompanyId">
            <el-select filterable v-model="queryParams.startCompanyId" placeholder="请选择企业" clearable>
              <el-option v-for="company in companies" :key="company.companyUuid" :label="company.companyName"
                :value="company.companyUuid" />
            </el-select>
          </el-form-item>

        </el-col>
      <el-col :span="8">
        <el-form-item label="回单是否已收齐" prop="isOfferedToDriver">
            <el-select v-model="queryParams.isReceiptReceivedAll" placeholder="请选择回单是否已收齐状态" clearable>
              <el-option v-for="option in getOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="运输人员" prop="transportId">
            <el-select filterable v-model="queryParams.transportId" placeholder="请选择运输人" clearable>
              <el-option v-for="driver in drivers" :key="driver.driverUuid" :label="driver.driverName"
                :value="driver.driverUuid" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
              <el-col :span="8">
          <el-form-item label="订单开始日期" prop="orderStartDateRange">
            <el-date-picker clearable v-model="queryParams.orderStartDateRange" type="daterange"
              value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"
              @change="handleDateStartRangeChange" placeholder="请选择订单开始日期范围" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单结束日期" prop="orderEndDateRange">
            <el-date-picker clearable v-model="queryParams.orderEndDateRange" type="daterange" value-format="yyyy-MM-dd"
              start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" @change="handleDateEndRangeChange"
              placeholder="请选择订单结束日期范围" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="是否已支付" prop="isOfferedToDriver">
            <el-select v-model="queryParams.isOfferedToDriver" placeholder="请选择支付状态" clearable>
              <el-option v-for="option in paymentOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3" class="text-right">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">
            搜索
          </el-button>
        </el-col>
        <el-col :span="3" class="text-right">
          <el-button icon="el-icon-refresh" @click="resetQuery">
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['order:order:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['order:order:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 订单列表表格 -->
    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderUuid" />
      <el-table-column label="订单开始日期" align="center" prop="orderStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderStartTime, '{y}-{m}-{d} ') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运输人" align="center" prop="driverName" />
      <el-table-column label="始发地企业" align="center" prop="startCompanyName" />
      <el-table-column label="目的地企业" align="center" prop="desCompanyName" />
      <el-table-column label="卸货地址" align="center" prop="desAddress" />
      <el-table-column label="企业金额（元）" align="center" prop="companyOffer" />
      <el-table-column label="驾驶员基本运费（元）" align="center" prop="driverOffer" />
      <el-table-column label="装卸费（元）" align="center" prop="loadUnloadFee" />
      <el-table-column label="驾驶员金额（运费+装卸费)(元)" align="center" prop="needOfferToDriver">
        <template slot-scope="scope">
          <span :class="{ 'highlight-bg': scope.row.needOfferToDriver !== 0 }">{{ scope.row.needOfferToDriver }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="已支付给驾驶员金额(元)" align="center" prop="hasOfferToDriver">
        <template slot-scope="scope">
          <span :class="{ 'highlight-bg': scope.row.hasOfferToDriver !== 0 }">{{ scope.row.hasOfferToDriver }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="还需支付给驾驶员金额(元)" align="center" prop="notHasOfferdToDriver">
        <template slot-scope="scope">
          <span :class="{ 'highlight-bg': scope.row.notHasOfferdToDriver !== 0 }">{{ scope.row.notHasOfferdToDriver }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="是否已支付给驾驶员(装卸费+驾驶员基本运费)" align="center" prop="isOfferedToDriver">
        <template slot-scope="scope">
          <span :class="scope.row.isOfferedToDriver === '1' ? 'paid' : 'not-paid'">{{ scope.row.isOfferedToDriver ===
            "1" ? '已支付' : '未支付' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付给驾驶员日期" align="center" prop="offeredData" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.offeredData, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回单是否已经收齐" align="center" prop="isReceiptReceivedAll">
        <template slot-scope="scope">
          <span :class="scope.row.isReceiptReceivedAll === '1' ? 'paid' : 'not-paid'">{{ scope.row.isReceiptReceivedAll ===
            "1" ? '已收齐' : '未收齐' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="盈利（元）" align="center" prop="profit">
        <template slot-scope="scope">
          <span :class="{ 'highlight-bg': scope.row.profit !== 0 }">
            {{ scope.row.profit }}
          </span>
        </template> -->
      <!-- </el-table-column> -->

      <el-table-column label="载货量(吨)" align="center" prop="cargoCapacity" />

      <el-table-column label="订单结束日期" align="center" prop="orderEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>


      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['order:order:edit']">
            修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openDetails(scope.row)"
            v-hasPermi="['order:order:query']">
            详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['order:order:remove']">
            删除
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleReceipt(scope.row)"
            v-hasPermi="['order:receipt']">
            操作回单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改订单弹窗 -->
    <insert :visible.sync="formVisible" :title="formTitle" :mode="formMode" :formData="currentFormData"
      @submit="handleFormSubmit" />
    <!-- 订单详情弹窗 -->
    <OrderDetailsVue :visible.sync="detailsVisible" :orderId="selectedOrderId" />
    <!-- 回单弹窗 -->
    <receiptVue :visible.sync="receiptVisible" :orderId="companyOrderUuid" />
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/fincal/order";
import { selectAllCompanylist } from "@/api/fincal/company";
import { selectAllDriverlist } from "@/api/fincal/driver";
import insert from "@/views/fincal/order/insert.vue"; // 确保路径正确
import receiptVue from "@/views/fincal/order/receipt.vue"; // 确保路径正确
import OrderDetailsVue from "@/views/fincal/order/OrderDetails.vue"; // 确保路径正确
export default {
  name: "Order",
  components: {
    insert,
    OrderDetailsVue,
    receiptVue
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 用于保存企业列表
      companies: [],
      // 用于保存驾驶员列表
      drivers: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      orderList: [],
      // 弹出层标题
      formTitle: "",
      // 是否显示弹出层
      formVisible: false,
      // 控制详情弹窗的显示
      detailsVisible: false,
      // 回单弹窗的显示
      receiptVisible: false,
      formMode: "",
      // 选中的订单 ID
      selectedOrderId: "",
      // 当前表单数据（用于新增或修改）
      currentFormData: {},
      // 回单数据
      companyOrderUuid: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startCompanyId: "",
        startCompanyName: "",
        desCompanyId: "",
        desCompanyName: "",
        transportId: "",
        driverName: "",
        driverOffer: "",
        companyOffer: "",
        cargoCapacity: "",
        orderStartTime: "",
        orderEndTime: "",
        isOfferedToDriver: "",
        orderStartStartTime: "",
        orderStartEndTime: "",
        orderEndStartTime: "",
        orderEndEndTime: "",
        isReceiptReceivedAll: "",
        loadUnloadFee: "",
        desAddress: "",
        offeredData: "",
        // 订单开始日期范围
        orderStartDateRange: [],
        // 订单结束日期范围
        orderEndDateRange: [],
      },
      paymentOptions: [
        { value: "1", label: '已支付' },
        { value: "0", label: '未支付' }
      ],
      getOptions: [
        { value: "1", label: '已收齐' },
        { value: "0", label: '未收齐' }
      ]
    };
  },
  created() {
    this.getList();
    this.loadCompanies(); // 加载企业数据
    this.loadDrivers(); // 加载驾驶员数据
  },
  methods: {
    /** 打开订单详情弹窗 */
    openDetails(row) {
      this.selectedOrderId = row.id;
      this.detailsVisible = true;
    },
    handleDateStartRangeChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.orderStartStartTime = dates[0]; // 设置开始日期
        this.queryParams.orderStartEndTime = dates[1];   // 设置结束日期
      } else {
        this.queryParams.orderStartStartTime = "";
        this.queryParams.orderStartEndTime = "";
      }
    },
    handleDateEndRangeChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.orderEndStartTime = dates[0]; // 设置开始日期
        this.queryParams.orderEndEndTime = dates[1];   // 设置结束日期
      } else {
        this.queryParams.orderEndStartTime = "";
        this.queryParams.orderEndEndTime = "";
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 加载企业列表 */
    loadCompanies() {
      this.loading = true;
      selectAllCompanylist(this.queryParams).then(response => {
        this.companies = response.data;
        this.loading = false;
      }).catch((error) => {
        console.error("获取企业列表失败:", error);
        this.loading = false;
      });
    },
    /** 加载驾驶员列表 */
    loadDrivers() {
      this.loading = true;
      selectAllDriverlist(this.queryParams).then(response => {
        this.drivers = response.data;
        this.loading = false;
      }).catch((error) => {
        console.error("获取驾驶员列表失败:", error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.formVisible = false;
      this.formMode = "";
      this.resetForm();
    },
    // 表单重置
    resetForm() {
      this.formMode = "";
      this.currentFormData = {
        id: "",
        startCompanyId: "",
        startCompanyName: "",
        desCompanyId: "",
        desCompanyName: "",
        transportId: "",
        driverName: "",
        driverOffer: "",
        companyOffer: "",
        remark: "",
        cargoCapacity: "",
        orderStartTime: "",
        orderEndTime: "",
        isOfferedToDriver: "",
        createdBy: "",
        createdTime: "",
        updatedBy: "",
        updatedTime: "",
        deleted: "",
        image: "",
        details: "",
        isReceiptReceivedAll: "",
        loadUnloadFee: "",
        desAddress: "",
        offeredData: "",
        // 订单开始日期范围
        orderStartDateRange: [],
        // 订单结束日期范围
        orderEndDateRange: [],
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.orderEndDateRange = [],
        this.orderEndDateRange = [],
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          startCompanyId: "",
          startCompanyName: "",
          desCompanyId: "",
          desCompanyName: "",
          transportId: "",
          driverName: "",
          driverOffer: "",
          companyOffer: "",
          cargoCapacity: "",
          orderStartTime: "",
          orderEndTime: "",
          isOfferedToDriver: "",
          orderStartStartTime: "",
          orderStartEndTime: "",
          orderEndStartTime: "",
          orderEndEndTime: "",
          isReceiptReceivedAll: "",
          loadUnloadFee: "",
          desAddress: "",
          offeredData: "",
          // 订单开始日期范围
          orderStartDateRange: [],
          // 订单结束日期范围
          orderEndDateRange: [],
        };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm();
      this.formTitle = "新增订单";
      this.formMode = "add"
      this.formVisible = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.formTitle = "修改订单";
      this.formMode = "edit"
      // 获取订单详情
      getOrder(row.id).then(response => {
        this.currentFormData = response.data;
        // 将 API 返回的日期字符串转换为 Date 对象
        if (this.currentFormData.orderStartTime) {
          this.currentFormData.orderStartTime = new Date(this.currentFormData.orderStartTime);
        }
        if (this.currentFormData.orderEndTime) {
          this.currentFormData.orderEndTime = new Date(this.currentFormData.orderEndTime);
        }
        this.formVisible = true;
      }).catch(() => {
        this.$modal.msgError("获取订单详情失败");
      });
    },
    //操作回单
    handleReceipt(row) {
      this.receiptVisible= true;
      this.companyOrderUuid=row.orderUuid;
    },
    /** 提交表单 */
    handleFormSubmit() {
      //刷新页面
      this.getList();
    },
    /** 取消表单 */
    handleFormCancel() {
      this.formVisible = false;
      this.resetForm();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除编号为"${ids}"的数据项？`).then(() => {
        return delOrder(ids);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fincal/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`);
    },
    /** 时间格式化函数 */
    parseTime(time, format) {
      if (!time) return '';
      const date = new Date(time);
      const map = {
        '{y}': date.getFullYear(),
        '{m}': ('0' + (date.getMonth() + 1)).slice(-2),
        '{d}': ('0' + date.getDate()).slice(-2),
        '{h}': ('0' + date.getHours()).slice(-2),
        '{i}': ('0' + date.getMinutes()).slice(-2),
        '{s}': ('0' + date.getSeconds()).slice(-2),
      };
      return format.replace(/{y}|{m}|{d}|{h}|{i}|{s}/g, (matched) => map[matched]);
    },
  }
};
</script>

<style scoped>
.highlight-bg {
  color: #ff0000;
  background-color: #57eca9;
  /* 浅红色背景 */
  padding: 2px 4px;
  border-radius: 4px;
}

.app-container {
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #f7f8fa;
}

.mb8 {
  margin-bottom: 8px;
}

.fixed-width {
  width: 120px;
  /* 根据需要调整 */
}

.small-padding {
  padding: 0 5px;
  /* 根据需要调整 */
}

.dialog-footer {
  text-align: right;
  /* 确保对话框的底部按钮对齐 */
}

/* 新增样式以美化搜索表单 */
.search-form {
  background-color: #ffffff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form .el-row {
  margin-bottom: 15px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.text-right {
  text-align: right;
}

.paid {
  color: green;
  font-weight: bold;
  /* 可选，用于突出显示 */
}

.not-paid {
  color: red;
  font-weight: bold;
  /* 可选，用于突出显示 */
}

@media (max-width: 768px) {
  .search-form .el-col {
    span: 24 !important;
  }

  .text-right {
    text-align: left;
    margin-top: 10px;
  }
}
</style>